package com.cpms.framework.common.utils;

import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;

/**
 * @description: jasypt加解密工具类
 * @author: gulang
 * @time: 2021/6/7 19:01
 */
public class CsJasyptUtils {

    // Singleton instance of StandardPBEStringEncryptor
    private static volatile PooledPBEStringEncryptor encryptor = createEncryptor();
    private static final String JASYPT_PASSWORD = "JASYPT_PASSWORD";

    // Private constructor to prevent instantiation
    private CsJasyptUtils() {
    }

    private static PooledPBEStringEncryptor createEncryptor() {
        if (encryptor == null) {
            synchronized (CsJasyptUtils.class) {
                if (encryptor == null) {
                    encryptor = new PooledPBEStringEncryptor();
                    encryptor.setConfig(cryptOr());
                }
            }
        }
        return encryptor;
    }

    /**
     * 获取秘钥
     * @return
     */
    private static String getJasyptPassword() {
        String jasyptPassword = System.getenv(JASYPT_PASSWORD);
        if(jasyptPassword ==null){
            throw new IllegalStateException("JASYPT_PASSWORD environment variable not set.");
        }
        return jasyptPassword;
    }

    /**
     * Jasypt生成加密结果
     * @param data    待加密值
     * @return
     */
    public static String encrypt(String data) {
        return encryptor.encrypt(data);
    }

    /**
     * 解密
     * @param encryptedData    待解密密文
     * @return
     */
    // Decryption method
    public static String decrypt(String encryptedData) {
        if (encryptor == null) {
            throw new IllegalStateException("Encryptor not initialized. Call initEncryptor first.");
        }
        return encryptor.decrypt(encryptedData);
    }

    public static SimpleStringPBEConfig cryptOr() {
        SimpleStringPBEConfig config = new SimpleStringPBEConfig();
        config.setPassword(getJasyptPassword());
        config.setAlgorithm("PBEWITHHMACSHA512ANDAES_256");
        config.setKeyObtentionIterations("1000");
        config.setPoolSize("5");
        config.setProviderName("SunJCE");
        config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
        config.setIvGeneratorClassName("org.jasypt.iv.RandomIvGenerator");
        config.setStringOutputType("base64");
        return config;
    }
}
